package org.gokeep.communication.engine.udp;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * 互联网地址信息
 *
 * @author xuning
 */
@Data
@Slf4j
public class InetAddress {
    public static final String BROADCAST_ADDRESS = "255.255.255.255";
    public static final String LOCAL_ADDRESS = "127.0.0.1";

    private String host;
    private int port;

    /**
     * 构建器
     *
     * @return
     */
    public static InetAddress build() {
        return new InetAddress();
    }

    /**
     * 构建器
     *
     * @param host
     * @param port
     * @return
     */
    public static InetAddress build(String host, int port) {
        return build().host(host).port(port);
    }

    /**
     * 设置主机
     *
     * @param host
     * @return
     */
    public InetAddress host(String host) {
        this.host = host;
        return this;
    }

    /**
     * 设置端口
     *
     * @param port
     * @return
     */
    public InetAddress port(int port) {
        this.port = port;
        return this;
    }

    /**
     * 获取socket连接地址
     *
     * @return
     */
    public InetSocketAddress socketAddress() {
        return new InetSocketAddress(this.host, this.port);
    }

    /**
     * 是否为组播地址
     * @return
     */
    public boolean isMulticastAddress() {
        try {
            return java.net.InetAddress.getByName(this.host).isMulticastAddress();
        } catch (UnknownHostException e) {
            log.warn("isMulticastAddress exception: ", e);
            return false;
        }
    }

    /**
     * 是否为广播地址
     * @return
     */
    public boolean isBroadcastAddress() {
        return BROADCAST_ADDRESS.equals(this.host);
    }
}
